package com.saltedfish.tool.ui.calendar

import android.Manifest
import android.os.Bundle
import android.os.Handler
import android.view.View
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import androidx.fragment.app.Fragment
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.viewpager.widget.ViewPager
import cn.droidlover.xdroidmvp.base.SimpleListener
import cn.droidlover.xdroidmvp.base.XFragmentAdapter
import cn.droidlover.xdroidmvp.event.BusProvider
import cn.droidlover.xdroidmvp.log.XLog
import cn.droidlover.xdroidmvp.mvp.XFragment
import cn.droidlover.xdroidmvp.util.AppUtil
import cn.droidlover.xdroidmvp.util.DateUtils
import com.blankj.rxbus.RxBus
import com.saltedfish.tool.R
import com.saltedfish.tool.constant.StringConstant
import com.saltedfish.tool.dao.AppDatabase
import com.saltedfish.tool.dialog.UICreateFlagDialog
import com.saltedfish.tool.model.FlagTable
import com.saltedfish.tool.model.ModelInfo
import com.saltedfish.tool.present.XFP
import com.saltedfish.tool.util.ViewClickUtils
import com.tencent.wcdb.database.SQLiteCipherSpec
import com.tencent.wcdb.room.db.WCDBOpenHelperFactory
import kotlinx.android.synthetic.main.fragment_calendar.*
import kotlinx.android.synthetic.main.fragment_calendar.btn_create
import kotlinx.android.synthetic.main.fragment_calendar.mViewPager
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

class FragmentCalendar : XFragment<XFP>(), View.OnClickListener{

    companion object {
        fun newInstance(): FragmentCalendar {
            return FragmentCalendar()
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_calendar
    }

    var today = ""
    var yesterday = ""
    var beforeday = ""
    override fun initData(savedInstanceState: Bundle?) {
        initRoom()

        BusProvider.getBus().subscribe(context,
                RxBus.Callback<ModelInfo> { modelInfo ->
                    if(modelInfo !=null && modelInfo.updateCalendar2){
                        updateFlagInfo()
                    }
                    if(modelInfo !=null && modelInfo.updateCalendar){
                            tv_Emoji.text = "\uD83D\uDC4D！完成了一项日程"
                            linearAnimation.visibility = View.VISIBLE
                            onTranslateInputAnimation(linearAnimation)
                    }
                })

    }

    override fun onResume() {
        super.onResume()
    }

    private var flagInfoLists: MutableList<FlagTable> = ArrayList()

    private var database: AppDatabase? = null

    override fun loadData() {
        super.loadData()
        ViewClickUtils.setViewClick(this, btn_create)
        updateFlagInfo()

    }

   private fun updateFlagInfo() {

       if(database !=null){
           var infoDao = database!!.flagInfoDao()
           var calendarDao = database!!.calenderDao()
           tvCalendarTitle.text = "今天日程"
           cal = Calendar.getInstance()
           cal!!.time =  Date()
           val sdf = SimpleDateFormat("MM月dd日")
           today = sdf.format(cal!!.time)
           var week = cal!!.get(Calendar.DAY_OF_WEEK)
           tvCalendarDate.text = today + printDayOfWeek(week)

           flagInfoLists = infoDao!!.all
           if(flagInfoLists.size !=0){
               mScrollView.visibility  = View.VISIBLE
               mVerticalText.text = "最多只能查看前天的日程哦！"
               mVerticalText.isCharCenter  = true
               mLinear_calender.visibility = View.GONE
               showTopData()

               yesterday = DateUtils.getYesterdayTime(cal,sdf)
               beforeday = DateUtils.getBeforedayTime(cal,sdf)

               //删除掉不是今天的日程提醒，那些保存在本地数据库的数据
               calendarDao.deleteAllByTime(today)

           }else{
               mScrollView.visibility  = View.GONE
               mLinear_calender.visibility = View.VISIBLE
           }
       }

    }


    private fun printDayOfWeek(week :Int) :String {
        var weekStr = ""
        when (week) {
            1 -> weekStr = "周日"
            2 -> weekStr = "周一"
            3 -> weekStr = "周二"
            4 -> weekStr = "周三"
            5 -> weekStr = "周四"
            6 -> weekStr = "周五"
            7 -> weekStr = "周六"
            else -> {
            }
        }
//        XLog.e("---33333---${weekStr}--")

        return weekStr;
    }

    private val fragmentList: MutableList<Fragment> = ArrayList()
    var adapter: XFragmentAdapter? = null
    var cal: Calendar? = null
    //显示顶部数据资源
    private fun showTopData() {
        fragmentList.clear()
        val fragment1 = FragmentBeforeday()
        val fragment2 = FragmentYesterday()
        val fragment3 = FragmentToday()

        fragmentList.add(fragment1)
        fragmentList.add(fragment2)
        fragmentList.add(fragment3)

        adapter = XFragmentAdapter(
            childFragmentManager,
            fragmentList
        )

//        mViewPager.offscreenPageLimit = 3
        mViewPager.adapter = adapter
        //默认显示今天
        mViewPager.currentItem = 2
        mViewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
            ) {}

            override fun onPageSelected(position: Int) {
                cal!!.time =  Date()
                var week = cal!!.get(Calendar.DAY_OF_WEEK)
                if(position == 0){
                    tvCalendarTitle.text = "前天日程"
                    if(week == 1){
                        week = 6
                    }else if(week == 2){
                        week = 7
                    }else{
                        week -= 2
                    }
                    tvCalendarDate.text = beforeday + printDayOfWeek(week)
                }else if(position == 1){
                    tvCalendarTitle.text = "昨天日程"
                    if(week == 1){
                        week = 7
                    }else{
                        week -= 1
                    }
                    tvCalendarDate.text = yesterday + printDayOfWeek(week)
                } else{
                    tvCalendarTitle.text = "今天日程"
                    tvCalendarDate.text = today + printDayOfWeek(week)
                }


            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
    }

    override fun newP(): XFP? {
        return null
    }





    private fun initRoom() {
        val cipherSpec = SQLiteCipherSpec()
            .setPageSize(4096)
            .setKDFIteration(64000)
        val factory =
            WCDBOpenHelperFactory() //  .passphrase("passphrase".getBytes())  // passphrase to the database, remove this line for plain-text
                .cipherSpec(cipherSpec) // cipher to use, remove for default settings
                // .writeAheadLoggingEnabled(false)       // enable WAL mode, remove if not needed
                .asyncCheckpointEnabled(true) // enable asynchronous checkpoint, remove if not needed
        database = Room.databaseBuilder(
            context,
            AppDatabase::class.java, StringConstant.DbBase
        )
            .allowMainThreadQueries()
            .setJournalMode(RoomDatabase.JournalMode.TRUNCATE)
            .openHelperFactory(factory) // specify WCDBOpenHelperFactory when opening database
            .build()
    }

    private val mHandler = Handler()

    //说明的功能课顶部弹出平移抖动动画
    private fun onTranslateInputAnimation(view: View) {
        val translateAnimation: Animation = TranslateAnimation(0.2f, 1f, (-1000).toFloat(), 0f)
        // translateAnimation.interpolator = CycleInterpolator(0.4f)
        translateAnimation.duration = 800
        translateAnimation.fillAfter = false
        //  translateAnimation.repeatMode = Animation.REVERSE
        view.startAnimation(translateAnimation)

            mHandler.postDelayed(Runnable {
                val translateAnimation: Animation = TranslateAnimation(0f, 0f, 0f, (-1000).toFloat())
                translateAnimation.duration = 800
                translateAnimation.fillAfter = false
                view.startAnimation(translateAnimation)
                linearAnimation.visibility = View.GONE

            }, 2200)


    }


    override fun onClick(v: View?) {
        when (v?.id) {

            R.id.btn_create -> {
                checkStoragePermission()
            }

        }
    }


    //检查相关权限
    private fun checkStoragePermission() {
        if (
            rxPermissions.isGranted(Manifest.permission.READ_CALENDAR)
            && rxPermissions.isGranted(Manifest.permission.WRITE_CALENDAR)
            && rxPermissions.isGranted(Manifest.permission.READ_EXTERNAL_STORAGE)
            && rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        ) {
            initCreateFalgView()
        } else {
            rxPermissions.request(
                Manifest.permission.READ_CALENDAR,
                Manifest.permission.WRITE_CALENDAR,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
            ).subscribe { t ->
                if (t) {
                    initCreateFalgView()
                }
            }.isDisposed
        }

    }

    private var  createFlagDialog : UICreateFlagDialog? =null

    /**
     * 创建Flag
     */
    private fun initCreateFalgView() {

   //     if (createFlagDialog == null) {
            createFlagDialog = UICreateFlagDialog(context,database)
            createFlagDialog!!.setSimpleListener(object : SimpleListener<Int>() {
                override fun onClick(type: String) {
//                    if (type == "save") {
//                        createFlagDialog!!.dismiss()
//
//                    }
                }
            })
  //      }
        createFlagDialog!!.setOnKeyBackListener(false)
        createFlagDialog!!.show()
        mHandler.postDelayed({
            AppUtil.showSoftInput(context)
        }, 500)

    }
}